const { UserList, UserJoin, Message } = require("../models/chat");

module.exports = function setupSockets(io) {
  io.on("connection", async (socket) => {
    const username = socket.handshake.query.username;
    // 查找数据库是否存在用户，进行创建或更新
    try {
      // 查找用户信息
      let userInfo = await UserList.findOne({ username }).exec();
      if (userInfo) {
        await UserList.findOneAndUpdate(
          { username: username },
          { $set: { id: socket.id } }
        ).exec();

        // 更新用户的 socket id
        userInfo.id = socket.id;
        await userInfo.save();
      } else {
        // 创建新的用户信息
        const newUser = new UserList({
          id: socket.id,
          username,
        });
        await newUser.save();
      }
    } catch (err) {
      console.error(err);
    }

    // 处理断开连接事件
    socket.on("disconnect", async () => {
      try {
        // 删除用户信息
        await UserList.findOneAndDelete({ id: socket.id }).exec();
      } catch (err) {
        console.error(err);
      }
    });

    // 对方同意好友请求对自身进行刷新
    socket.on("agreeUser", async (username) => {
      let name = username.addUserName;
      let userInfo = await UserList.findOne({ username: name }).exec();
      io.to(userInfo.id).emit("refreshUserList");
    });

    socket.on("privateMsg", async (msg) => {
      let username = msg.from === msg.to?.user1 ? msg.to?.user2 : msg.to?.user1;
      let toUserInfo = await UserList.findOne({ username: username }).exec();

      io.to(toUserInfo.id).emit("privateMsg", msg);

      const newMessage = new Message({
        from: msg.from,
        to: username,
        message: msg.message,
      });
      await newMessage.save();

      // 更新用户最新消息字段
      await UserJoin.findOneAndUpdate(
        {
          $or: [
            { user1: msg.from, user2: username },
            { user1: username, user2: msg.from },
          ],
        },
        {
          $set: {
            lastmsg: msg.message,
            msgtime: msg.time,
            to: username,
          },
          $inc: {
            isread: 1, // 将isread字段的值默认加1
          },
        },
        { new: true } // 设置为true表示返回更新后的数据
      ).exec();
    });
  });
};
